﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Web.UI.WebControls;
using System.Web;

namespace Card.Common
{
    public class CardWebUtility
    {
        public static void SetCartInfo(int userID)
        {
            Card.Security.CookieManager.AddCookie(CONST.CookieNames.CartRecord, BLL.CartManager.Count(userID).ToString());
        }

        public static string CreateOrderID()
        {
            return string.Format("{0}{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), BAF.BLL.SYSSequenceManager.GetSequence(CONST.SEQUENCE_CODE.ORDER_ID, null));
        }
        /// <summary>
        /// 得到订单状态
        /// </summary>
        /// <param name="orderStatus"></param>
        /// <returns></returns>
        public static string GetOrderStatusDesc(string orderStatus)
        {
            switch (orderStatus.ToUpper().Trim())
            {
                case CONST.ORDER_SATTUS.WAIT_PAY:
                    return "待付款";
                case CONST.ORDER_SATTUS.WAIT_CONFIRM:
                    return "待确认";
                case CONST.ORDER_SATTUS.WAIT_MAKE:
                    return "待制作";
                case CONST.ORDER_SATTUS.WAIT_DELIVER:
                    return "待发货";
                case CONST.ORDER_SATTUS.ALREADY_DELIVER:
                    return "已发货";
                case CONST.ORDER_SATTUS.COMPLETE:
                    return "交易完成";
            }
            return string.Empty;
        }
        /// <summary>
        /// 删除Order Card 文件
        /// </summary>
        /// <param name="orderCardID"></param>
        /// <param name="passport"></param>
        /// <returns></returns>
        public static bool DeleteOrderCardFiles(int orderCardID,Card.Security.Passport passport)
        {
            string url = string.Format("{0}/ImageService.ashx?a=doc&id={1}&uid={2}", Card.Utility.ImageUtilty.ImageServer, orderCardID, passport.UserID);
            WebRequest request = HttpWebRequest.Create(url);
            request.Method = "GET";
            request.Headers.Add("Cookie", string.Format("{0}={1}", Card.CONST.CookieNames.Passport, passport));

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            using (StreamReader dataStream = new StreamReader(response.GetResponseStream()))
            {
                var result = dataStream.ReadToEnd();
                JObject jResult = (JObject)JsonConvert.DeserializeObject(result);
                if (string.Compare(jResult.Property("r").Value.ToString(), CONST.YES_NO.YES, true) == 0)
                {
                    return true;
                }
            }
            return false;
        }
        /// <summary>
        /// 绑定订单状态到Dropdowlist
        /// </summary>
        /// <param name="lst"></param>
        /// <param name="insertAll"></param>
        public static void BindOrderStatus(ListControl ltc, bool insertAll)
        {
            if (insertAll)
            {
                ltc.Items.Add(new ListItem("--全部--", ""));
            }
            ltc.Items.Add(new ListItem("待付款", CONST.ORDER_SATTUS.WAIT_PAY));
            ltc.Items.Add(new ListItem("待确认", CONST.ORDER_SATTUS.WAIT_CONFIRM));
            ltc.Items.Add(new ListItem("待制作", CONST.ORDER_SATTUS.WAIT_MAKE));
            ltc.Items.Add(new ListItem("待发货", CONST.ORDER_SATTUS.WAIT_DELIVER));
            ltc.Items.Add(new ListItem("已发货", CONST.ORDER_SATTUS.ALREADY_DELIVER));
            ltc.Items.Add(new ListItem("交易完成", CONST.ORDER_SATTUS.COMPLETE));
        }

   
        public static string CreateFieldHTML(
            string faceType,
            string sort,
            string content,
            string posX,
            string posY,
            string direction,
            string color,
            string fontFamily,
            string fontSize,
            string fontStyle
            )
        {
            string template = @"
<li>
    <table border='0'id='{0}_tb_{1}' >
        <tr>
            <td><input class='rpttxt' maxlength='100' id='{0}_txt_{1}' s='{1}' value='{2}' x='{3}' y='{4}' d='{5}' fc='{6}' fs='{8}' ff='{9}' fst='{10}' />
                <a href='javascript:void(0);'  onclick=javascript:modify_detail('{0}','{1}') ><img src='/images/m.gif' title='修改' width='20px' height='20px' border='0' /></a></td>
        </tr>
        <tr style='display:none' id='{0}_tr_{1}' class='d_tr'  f='{0}' s='{1}'>
            <td>            
                <div  class='fl h30'>
                    <span class='txt'>颜色</span><span class='color'><input f='{0}' s='{1}' id='c_{0}_txt_{1}' value='{6}' style='width:1px;display:none;'></span>
                </div>
                <div  class='fl h30' >
                     <span class='txt'>字体</span>
                     <span><select id='{0}_ff_{1}' onchange=javascript:chage_family('{0}','{1}','{5}') >{7}</select></span>                     
                 </div>
                 <div  class='fl h30' id='{0}_fts_{1}'>
                       <div class='f_style bold' v='B' s='{0}' f='{1}' onclick=set_style(this,'{0}','{1}','{5}') ></div>
                       <div class='f_style italic'  v='I'  s='{0}' f='{1}'  onclick=set_style(this,'{0}','{1}','{5}') ></div>
                       <div class='f_style underline'  v='U'  s='{0}' f='{1}' onclick=set_style(this,'{0}','{1}','{5}') ></div>
                 </div>
                 <div class='fl h30' style='margin-left:10px;'>
                        <span style='height:20px'>
                          <dl class='math_mark_add' style='float:left' onclick=javascript:chage_font_size(1,'{0}','{1}') ></dl>
                          <dl class='math_mark_sub' style='float:left' onclick=javascript:chage_font_size(-1,'{0}','{1}') ></dl>
                     </span>
                     <span style='float:right;display:none'><a href='javascript:void(0);' onclick=javascript:delete_image('{0}','{1}') ><img src='/images/d.jpg' title='删除' width='20px' height='20px' border='0' /></a></span>
                 </div>
            </td>
        </tr>
    </table>
</li>";

            return string.Format(template,
                                  faceType,
                                  sort,
                                  content,
                                  posX,
                                  posY,
                                  direction,
                                  color,
                                  GetFontFamilyOptions(fontFamily),
                                  fontSize,
                                  fontFamily,
                                  string.IsNullOrEmpty(fontStyle) ? CONST.FontStyle.Regular : fontStyle);
        }

        private static string GetFontFamilyOptions(string defaultFamily)
        {
            StringBuilder sbOptions = new StringBuilder();
            List<BAF.Entity.LookupValue> _FontFamily = Card.Common.LookUpCache.GetLookupValues(CONST.LOOKUP_TYPE.FONT_FAMILY);
            if (_FontFamily != null)
            {
                foreach (BAF.Entity.LookupValue family in _FontFamily)
                {
                    sbOptions.Append("<option value='")
                        .Append(family.LookupCode)
                        .Append(string.Compare(family.LookupCode, defaultFamily) == 0 ? "' selected >" : "' >")
                        .Append(family.Value)
                        .Append("</option>");
                }
            }
            return sbOptions.ToString();
        }

        public static string CreateFieldImageHTML(string sort, string faceType)
        {

            return string.Format("<img id='{0}Img{1}' alt='按鼠标左键移动字段' t='{0}' s='{1}' style='z-index:99;border:0px;'  />", faceType, sort);
        }

        public static string CreateLogoHTML(Entity.TemplateLogo logo)
        {
            return string.Format("<img id='{0}LImg'  style='border:0px;z-index:98;width:{1}px;height:{2}px;left:{3}px;top:{4}px;position: relative;' w='{1}' h='{2}'  ow='{1}' oh='{2}' x='{3}' y='{4}'  src='{5}' p='{6}' class='mplogo' />",
                    logo.ImageType, logo.Width, logo.Height, logo.PosX, logo.PosY, Card.Utility.ImageUtilty.GetLogoPath(logo.Logo), logo.Logo);
        }

        public static string CreateUserCardLogoHTML(Entity.UserCardLogo logo)
        {
            return string.Format("<img id='{0}LImg' style='border:0px;z-index:98;width:{1}px;height:{2}px;left:{3}px;top:{4}px;position: relative;' w='{1}' h='{2}'  ow='{1}' oh='{2}' x='{3}' y='{4}'  src='{5}' p='{6}' class='mplogo' />",
                    logo.ImageType, logo.Width, logo.Height, logo.PosX, logo.PosY, Card.Utility.ImageUtilty.GetLogoPath(logo.Logo), logo.Logo);
        }

        public static string GetAreaCode()
        {
            string code = string.Empty;
            int length = HttpContext.Current.Request.Url.Host.IndexOf('.');
            if (length > 0)
            {
                code = HttpContext.Current.Request.Url.Host.Substring(0, length).Trim();                
            }
            return code;
        }

        ///// <summary>
        ///// 区域
        ///// </summary>
        //public static Card.Entity.Area GetDefaultCity()
        //{
        //    string code = string.Empty;
        //    Card.Entity.Area area = null;
        //    int length = HttpContext.Current.Request.Url.Host.IndexOf('.');
        //    if (length > 0)
        //    {
        //        code = HttpContext.Current.Request.Url.Host.Substring(0, length);
        //        area = Card.Common.AreaCache.GetAreaByCode(code);
        //    }
        //    if (area == null || string.Compare(area.IsActive, CONST.YES_NO.YES) != 0)
        //    {
        //        area = Card.Common.CardWebUtility Card.Security.CookieManager.GetCity()));    
        //    }
        //    if (area == null || string.Compare(area.IsActive, CONST.YES_NO.YES) != 0)
        //    {
        //        area = Card.Common.CardWebUtility.ParseCity(Common.LookUpCache.GetLookupValue(CONST.LOOKUP_TYPE.CITY, CONST.MainCity));    
        //    }
        //    if (area != null)
        //    {
        //        Card.Security.CookieManager.SetCity(area.Code);
        //    }
            

        //    return area;
        //}

        //public static Card.Entity.City GetCity(string cityCode)
        //{
        //    return Card.Common.CardWebUtility.ParseCity(Common.LookUpCache.GetLookupValue(CONST.LOOKUP_TYPE.CITY, cityCode));
        //}
        /// <summary>
        /// 得到网站名称
        /// </summary>
        /// <returns></returns>
        public static string GetSiteName()
        {
            BAF.Entity.LookupValue lookup = Common.LookUpCache.GetLookupValue(CONST.LOOKUP_TYPE.SYSTEM_CONFIG, CONST.SYSTEM_CONFIG_CODE.SITE_NAME);
            return lookup == null ? string.Empty : lookup.Value;
        }

        /// <summary>
        /// 得到网站主域
        /// </summary>
        /// <returns></returns>
        public static string GetSiteDomain()
        {
            BAF.Entity.LookupValue lookup = Common.LookUpCache.GetLookupValue(CONST.LOOKUP_TYPE.SYSTEM_CONFIG, CONST.SYSTEM_CONFIG_CODE.SITE_DOMAIN);
            return lookup == null ? string.Empty : lookup.Value;
        }
    }
}
